<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\model\dealer;

use think\facade\Cache;
use cores\exception\BaseException;
use app\common\model\dealer\Setting as SettingModel;

/**
 * 分销商设置模型
 * Class Setting
 * @package app\store\model\dealer
 */
class Setting extends SettingModel
{
    /**
     * 设置项描述
     * @var array
     */
    private array $describe = [
        'basic' => '基础设置',
        'condition' => '分销商条件',
        'commission' => '佣金设置',
        'settlement' => '结算',
        'words' => '自定义文字',
        'license' => '申请协议',
        'background' => '页面背景图',
        'poster' => '分销海报',
    ];

    /**
     * 更新系统设置
     * @param array $data
     * @return bool
     */
    public function edit(array $data): bool
    {
        $this->transaction(function () use ($data) {
            foreach ($data as $key => $values) {
                $this->saveValues($key, $values);
            }
            // 删除系统设置缓存
            Cache::delete('dealer_setting_' . self::$storeId);
        });
        return true;
    }

    /**
     * 保存设置项
     * @param $key
     * @param $values
     * @return void
     * @throws BaseException
     */
    private function saveValues($key, $values): void
    {
        // 数据验证
        if (!$this->validValues($key, $values)) {
            throwError($this->error);
        }
        $model = self::detail($key) ?: new self;
        $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'update_time' => time(),
            'store_id' => self::$storeId,
        ]);
    }

    /**
     * 数据验证
     * @param $key
     * @param $values
     * @return bool
     */
    private function validValues($key, $values): bool
    {
        if ($key === 'settlement') {
            // 验证结算方式
            return $this->validSettlement($values);
        }
//        if ($key === 'condition') {
//            // 验证分销商条件
//            return $this->validCondition($values);
//        }
        return true;
    }

    /**
     * 验证结算方式
     * @param $values
     * @return bool
     */
    private function validSettlement($values): bool
    {
        if (empty($values['pay_type'])) {
            $this->error = '请设置 结算-提现方式';
            return false;
        }
        return true;
    }
}